from rest_framework import serializers
from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer

from .models import *


class LabelSerializer(ModelSerializer):
    class Meta:
        model = Label
        fields = "__all__"


class ArticleSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.username', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    label_name = serializers.CharField(source='label.name', read_only=True)

    class Meta:
        model = Article
        exclude = ['is_delete']

        extra_kwargs = {
            "page_view": {"read_only": True},
            "priority": {"read_only": True}
        }


class CommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.username', read_only=True)
    son_comment_count = SerializerMethodField(read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    class Meta:
        model = Comment
        exclude = ['is_delete']

    def get_son_comment_count(self, comment):
        return comment.parent_comment_set.count()


class SonCommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.username', read_only=True)
    reply_username = serializers.CharField(source='replay_comment.user.username', read_only=True)

    class Meta:
        model = Comment
        exclude = ['is_delete']
